這個得上一篇:https://ithelp.ithome.com.tw/articles/10258345
讓購物車可以真的作動
先從cmd新增使用語法ng generate class common/cart-item:
從檔案cart-item.ts新增:
要import product就是紅線上的錯誤->快速修復
import { Product } from './product';
export class CartItem {
id:string;
name:string;
imageUrl:string;
unitPrice:number;
quantity:number;
constructor(product: Product){
this.id = product.id;
this.name = product.name;
this.imageUrl = product.imageUrl;
this.unitPrice = product.unitPrice;
this.quantity=1;
}
}
先從cmd新增使用語法ng generate service services/cart
再來從檔案cart.service.ts新增:
要import CartItem就是紅線上的錯誤->快速修復
import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
CartItems: CartItem[]=[];
totalPrice: Subject<number> = new Subject<number>();
totalQuantity: Subject<number> = new Subject<number>();
constructor() { }
}
然後後面要陸續新增確認物品有在購物車->用id找到->照到了
computeCartTotals也是要修正
import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
CartItems: CartItem[]=[];
totalPrice: Subject<number> = new Subject<number>();
totalQuantity: Subject<number> = new Subject<number>();
constructor() { }
addToCart(theCartItem:CartItem){
let alreadyExistsInCart : boolean = false;
let existingCartItem: CartItem = undefined;
if (this.CartItems.length>0){
for(let tempCartItem of this.CartItems){
if(tempCartItem.id === theCartItem.id){
existingCartItem =tempCartItem;
break;
}
}
alreadyExistsInCart =(existingCartItem != undefined);
}
if (alreadyExistsInCart){
existingCartItem.quantity++;
}
else{
this.CartItems.push(theCartItem);
}
this.computeCartTotals();
}
computeCartTotals() {
throw new Error("Method not implemented.");
}
}
接著再修正語法 throw new Error("Method not implemented.");
totalPriceValue也是要修正->按快速修復會產生這個方法
import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
CartItems: CartItem[]=[];
totalPrice: Subject<number> = new Subject<number>();
totalQuantity: Subject<number> = new Subject<number>();
constructor() { }
addToCart(theCartItem:CartItem){
let alreadyExistsInCart : boolean = false;
let existingCartItem: CartItem = undefined;
if (this.CartItems.length>0){
for(let tempCartItem of this.CartItems){
if(tempCartItem.id === theCartItem.id){
existingCartItem =tempCartItem;
break;
}
}
alreadyExistsInCart =(existingCartItem != undefined);
}
if (alreadyExistsInCart){
existingCartItem.quantity++;
}
else{
this.CartItems.push(theCartItem);
}
this.computeCartTotals();
}
computeCartTotals() {
let totalPriceValue: number =0;
let totalQuantityValue: number =0;
for(let currentCartItem of this.CartItems){
totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
totalQuantityValue += currentCartItem.quantity;
}
this.totalPrice.next(totalPriceValue);
this.totalQuantity.next(totalQuantityValue);
this.logCartData(totalPriceValue, totalQuantityValue);
}
logCartData(totalPriceValue: number, totalQuantityValue: number) {
throw new Error("Method not implemented.");
}
}
然後再繼續修正編寫:
import { CartItem } from './../common/cart-item';
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartService {
CartItems: CartItem[]=[];
totalPrice: Subject<number> = new Subject<number>();
totalQuantity: Subject<number> = new Subject<number>();
constructor() { }
addToCart(theCartItem:CartItem){
let alreadyExistsInCart : boolean = false;
let existingCartItem: CartItem = undefined;
if (this.CartItems.length>0){
for(let tempCartItem of this.CartItems){
if(tempCartItem.id === theCartItem.id){
existingCartItem =tempCartItem;
break;
}
}
alreadyExistsInCart =(existingCartItem != undefined);
}
if (alreadyExistsInCart){
existingCartItem.quantity++;
}
else{
this.CartItems.push(theCartItem);
}
this.computeCartTotals();
}
computeCartTotals() {
let totalPriceValue: number =0;
let totalQuantityValue: number =0;
for(let currentCartItem of this.CartItems){
totalPriceValue += currentCartItem.quantity * currentCartItem.unitPrice;
totalQuantityValue += currentCartItem.quantity;
}
this.totalPrice.next(totalPriceValue);
this.totalQuantity.next(totalQuantityValue);
this.logCartData(totalPriceValue, totalQuantityValue);
}
logCartData(totalPriceValue: number, totalQuantityValue: number) {
console.log('Contents of the cart');
for (let tempCartItem of this.CartItems){
const subTotalPrice = tempCartItem.quantity * tempCartItem.unitPrice;
console.log(`name: ${tempCartItem.name}, quantity=${tempCartItem.quantity},unitPrice=${tempCartItem.unitPrice},subTotalPrice=${subTotalPrice}`);
}
console.log(`totalPrice: ${totalPriceValue.toFixed(2)}, totalQuantity: ${totalPriceValue}`);
console.log('----');
}
}
再到product-list.component.ts檔案修改
到檔案下面新增
import { CartService } from './../../services/cart.service';
import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/product.service';
import { Product } from 'src/app/common/product';
import { ActivatedRoute } from '@angular/router';
import { CartItem } from 'src/app/common/cart-item';
@Component({
selector: 'app-product-list',
templateUrl: './product-list-grid.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
products: Product[];
currentCategoryId: number = 1;
previousCategoryId: number=1;
searchMode: boolean = false;
thePageNumber: number = 1;
thePageSize: number = 5;
theTotalElements: number = 0;
previousKeyword: string=null;
constructor(private productService: ProductService,
private CartService:CartService,
private Route: ActivatedRoute) { }
// tslint:disable-next-line: typedef
ngOnInit() {
this.Route.paramMap.subscribe(() => {
this.listProducts();
});
}
// tslint:disable-next-line: typedef
listProducts() {
this.searchMode = this.Route.snapshot.paramMap.has('keyword');
if (this.searchMode) {
this.handleSearchProducts();
}
else {
this.handleListProducts();
}
}
handleSearchProducts() {
const theKeyword: string = this.Route.snapshot.paramMap.get('keyword');
if(this.previousKeyword != theKeyword){
this.thePageNumber =1;
}
this.previousKeyword =theKeyword;
console.log(`keyword=${theKeyword},thePageNumber=${this.thePageNumber}`);
this.productService.searchProductsPaginate(this.thePageNumber -1,
this.thePageSize,
theKeyword).subscribe(this.processResult());
}
handleListProducts() {
const hasCategoryId: boolean = this.Route.snapshot.paramMap.has('id');
if (hasCategoryId) {
this.currentCategoryId = +this.Route.snapshot.paramMap.get('id');
}
else {
this.currentCategoryId = 1;
}
if (this.previousCategoryId != this.currentCategoryId) {
this.thePageNumber = 1;
}
this.previousCategoryId=this.currentCategoryId;
console.log(`currentCategoryId=${this.currentCategoryId},thePageNumber=${this.thePageNumber}`);
this.productService.getProductListPaginate(this.thePageNumber -1,
this.thePageSize,
this.currentCategoryId)
.subscribe(this.processResult());
}
processResult(){
return data =>{
this.products=data._embedded.products;
this.thePageNumber=data.page.number +1;
this.thePageSize =data.page.size;
this.theTotalElements =data.page.totalElements;
};
}
updatePageSize(pageSize: number){
this.thePageSize=pageSize;
this.thePageNumber=1;
this.listProducts();
}
addToCart(theProduct: Product){
console.log(`Adding to cart: ${theProduct.name},${theProduct.unitPrice}`);
const theCartItem =new CartItem(theProduct);
this.CartService.addToCart(theCartItem);
}
}
用chrome 的開發者工具試看到結果:
這個的下一篇:https://ithelp.ithome.com.tw/articles/10258409